const db = wx.cloud.database();
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    whatToadd: 0,
    userInfo: null,
    _openid: null,
    showAddDialog: false,
    formData: {},
    teamList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    console.log(options);
    this.setData({
      whatToadd: options.section
    });
    this.setData({
      userInfo: app.globalData.userInfo,
      _openid: app.globalData._openid
    });
    this.initIdeaList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * @brief 表单提交，检查文本内容是否填写完整，不检查图片
   */
  formSubmit: async function () {
    // 检查完整性
    var form = this.data.formData;
    if (form.title == '' || form.content == '' || form.title == null || form.content == null) {
      wx.showToast({
        title: '信息不完整',
        icon: 'error'
      });
      return;
    }
    var date = this.getDateStr();
    console.log('date', date);
    console.log('user', this.data.userInfo);
    // 确认提示
    var modalRes = await wx.showModal({
      title: '提示',
      content: '确定提交吗？',
      showCancel: true
    });
    if (modalRes.confirm) {
      // 上传图片到云存储
      if (that.data.formData.imgUrl != null) {
        var uploadRes = await wx.cloud.uploadFile({
          cloudPath: 'team_img/' + this.getRandFileName('png'),
          filePath: that.data.formData.imgUrl
        });
        console.log('upload res', uploadRes);
        // 修改formData
        that.setData({
          'formData.imgUrl': uploadRes.fileID
        });
      }
      // 添加想法
      db.collection('post').add({
        data: {
          type: 'idea',
          title: form.title,
          content: form.content,
          date: date,
          imgUrl: form.imgUrl
        }
      }).then((res) => {
        console.log('add success', res);
        wx.showToast({
          title: '成功'
        }).then((res) => {
          setTimeout(() => {
            wx.navigateBack();
          }, 800);
        });
      }).catch((res) => {
        console.log('add fail', res);
        wx.showModal({
          title: '提示',
          content: '提交失败',
          showCancel: false
        });
      });
    } else {
      return;
    }
  },

  /**
   * @brief 设置表单文FormData本内容
   * @param {*} arg titleedInput组件触发input事件传入的参数，具体数据在detail中
   */
  setFormData: function (arg) {
    console.log(arg);
    var name = arg.detail.name;
    var value = arg.detail.value;
    this.data.formData[name] = value;
    this.setData({
      formData: this.data.formData
    });
  },

  /**
   * @brief 获取当前日期字符串，格式为yyyy-mm-dd
   */
  getDateStr: function () {
    var d = new Date();
    var date = String(d.getFullYear()) + '-' + String(d.getMonth() + 1) + '-' + String(d.getDate()); // yyyy-mm-dd
    return date;
  },

  /**
   * 根据时间获取随机的文件名
   * @param {String} suffix 后缀
   */
  getRandFileName: function (suffix) {
    var d = new Date();
    var date = String(d.getFullYear()) + '-' +
      String(d.getMonth() + 1) + '-' +
      String(d.getDate()) + '-' +
      String(d.getHours()) + '-' +
      String(d.getMinutes()) + '-' +
      String(d.getSeconds()); // yyyy-mm-dd-hh-mm-ss
    return date + '.' + suffix;
  },

  /**
   * @brief 显示mp-halfscreendialog
   */
  showDialog: function () {
    console.log('dislog show');
    this.setData({
      showAddDialog: true
    });
  },

  /**
   * @brief 获取队伍列表
   * @todo 加入skip参数，每次只获取一定数量的队伍信息
   */
  initIdeaList: function () {
    wx.cloud.callFunction({
      name: 'getPostList',
      data: {
        skip: 0,
        type: 'idea'
      }
    }).then((res) => {
      console.log('team list', res);
      that.data.teamList = [];
      for (var i in res.result) {
        that.data.teamList.push({
          title: res.result[i].title,
          date: res.result[i].date,
          brief: res.result[i].content,
          ownerName: res.result[i].owner[0].nickName,
          ownerAvatar: res.result[i].owner[0].avatarUrl,
          comment: 0,
          like: 0,
          imgUrl: res.result[i].imgUrl,
          id: res.result[i]._id
        });
      }
      that.setData({
        teamList: that.data.teamList
      });
    }).catch((res) => {
      console.log('error: team list');
    })
  },

  /**
   * 设置FormData中图片的URL
   * @param {*} arg 组件触发change事件传入的参数，具体信息在detail中
   */
  setUpImg: function (arg) {
    console.log('add page img url', arg);
    this.setData({
      'formData.imgUrl': arg.detail.url
    });
  },

  /**
   * 转到队伍详情页面
   * @param {*} arg tap事件传入的参数
   */
  toArticle: function (arg) {
    console.log('tap article', arg);
    wx.navigateTo({
      url: '../article/index?type=team&id=' + arg.currentTarget.dataset.id,
    });
  }
})